<template>
  <div class="study-plan">
    <main class="main-content">
      <div class="container">
        <div class="page-header">
          <h1>学习计划</h1>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              新建计划
            </el-button>
          </div>
        </div>

        <div class="plan-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="进行中" name="active">
              <div class="plans-grid">
                <div
                  v-for="plan in activePlans"
                  :key="plan.id"
                  class="plan-card"
                >
                  <div class="plan-header">
                    <h3>{{ plan.title }}</h3>
                    <el-dropdown @command="handlePlanAction">
                      <el-button circle size="small">
                        <el-icon><MoreFilled /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="`edit:${plan.id}`"
                            >编辑</el-dropdown-item
                          >
                          <el-dropdown-item :command="`pause:${plan.id}`"
                            >暂停</el-dropdown-item
                          >
                          <el-dropdown-item
                            :command="`delete:${plan.id}`"
                            divided
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>

                  <p class="plan-description">{{ plan.description }}</p>

                  <div class="plan-progress">
                    <div class="progress-info">
                      <span>完成度</span>
                      <span>{{ plan.progress }}%</span>
                    </div>
                    <el-progress
                      :percentage="plan.progress"
                      :show-text="false"
                    />
                  </div>

                  <div class="plan-tasks">
                    <div class="tasks-header">
                      <span
                        >任务列表 ({{
                          plan.tasks.filter((t) => t.completed).length
                        }}/{{ plan.tasks.length }})</span
                      >
                    </div>
                    <div class="task-list">
                      <div
                        v-for="task in plan.tasks.slice(0, 3)"
                        :key="task.id"
                        class="task-item"
                      >
                        <el-checkbox
                          v-model="task.completed"
                          @change="
                            updateTaskStatus(plan.id, task.id, task.completed)
                          "
                        >
                          {{ task.title }}
                        </el-checkbox>
                        <span class="task-duration"
                          >{{ task.duration }}min</span
                        >
                      </div>
                      <div v-if="plan.tasks.length > 3" class="more-tasks">
                        还有 {{ plan.tasks.length - 3 }} 个任务...
                      </div>
                    </div>
                  </div>

                  <div class="plan-meta">
                    <div class="meta-item">
                      <el-icon><Calendar /></el-icon>
                      <span>{{ formatDate(plan.dueDate) }}</span>
                    </div>
                    <div class="meta-item">
                      <el-icon><Clock /></el-icon>
                      <span>{{ calculateDaysLeft(plan.dueDate) }}天剩余</span>
                    </div>
                  </div>

                  <div class="plan-actions">
                    <el-button size="small" @click="viewPlanDetail(plan)"
                      >查看详情</el-button
                    >
                    <el-button
                      size="small"
                      type="primary"
                      @click="startStudy(plan)"
                      >开始学习</el-button
                    >
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="已完成" name="completed">
              <div class="plans-grid">
                <div
                  v-for="plan in completedPlans"
                  :key="plan.id"
                  class="plan-card completed"
                >
                  <div class="plan-header">
                    <h3>{{ plan.title }}</h3>
                    <el-tag type="success">已完成</el-tag>
                  </div>
                  <p class="plan-description">{{ plan.description }}</p>
                  <div class="completion-info">
                    <el-icon color="#67c23a"><Check /></el-icon>
                    <span>于 {{ formatDate(plan.completedAt) }} 完成</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="已暂停" name="paused">
              <div class="plans-grid">
                <div
                  v-for="plan in pausedPlans"
                  :key="plan.id"
                  class="plan-card paused"
                >
                  <div class="plan-header">
                    <h3>{{ plan.title }}</h3>
                    <el-tag type="warning">已暂停</el-tag>
                  </div>
                  <p class="plan-description">{{ plan.description }}</p>
                  <div class="plan-actions">
                    <el-button
                      size="small"
                      type="primary"
                      @click="resumePlan(plan.id)"
                      >继续</el-button
                    >
                    <el-button size="small" @click="deletePlan(plan.id)"
                      >删除</el-button
                    >
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <div v-if="getCurrentPlans().length === 0" class="empty-state">
          <el-icon size="60" color="#c0c4cc"><Document /></el-icon>
          <p>{{ getEmptyMessage() }}</p>
          <el-button type="primary" @click="showCreateDialog = true"
            >创建第一个学习计划</el-button
          >
        </div>
      </div>
    </main>

    <!-- 创建计划对话框 -->
    <el-dialog v-model="showCreateDialog" title="创建学习计划" width="600px">
      <el-form
        :model="planForm"
        :rules="planRules"
        ref="planFormRef"
        label-width="100px"
      >
        <el-form-item label="计划名称" prop="title">
          <el-input v-model="planForm.title" placeholder="输入学习计划名称" />
        </el-form-item>

        <el-form-item label="计划描述" prop="description">
          <el-input
            v-model="planForm.description"
            type="textarea"
            :rows="3"
            placeholder="描述学习计划的目标和内容"
          />
        </el-form-item>

        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker
            v-model="planForm.dueDate"
            type="date"
            placeholder="选择截止日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="学习任务">
          <div class="tasks-editor">
            <div
              v-for="(task, index) in planForm.tasks"
              :key="index"
              class="task-editor"
            >
              <el-input
                v-model="task.title"
                placeholder="任务名称"
                style="flex: 1"
              />
              <el-input-number
                v-model="task.duration"
                :min="1"
                :max="480"
                placeholder="时长"
                style="width: 100px"
              />
              <el-button
                circle
                size="small"
                type="danger"
                @click="removeTask(index)"
                :disabled="planForm.tasks.length <= 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button size="small" @click="addTask">
              <el-icon><Plus /></el-icon>
              添加任务
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="AI辅助">
          <el-switch
            v-model="planForm.aiAssisted"
            active-text="启用AI辅助生成任务"
            inactive-text="手动创建任务"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createPlan" :loading="creating"
          >创建</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  MoreFilled,
  Calendar,
  Clock,
  Check,
  Document,
  Delete,
} from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";

const router = useRouter();
const userStore = useUserStore();

const activeTab = ref("active");
const showCreateDialog = ref(false);
const creating = ref(false);
const planFormRef = ref<FormInstance>();

const planForm = reactive({
  title: "",
  description: "",
  dueDate: "",
  tasks: [{ title: "", duration: 60, completed: false }],
  aiAssisted: true,
});

const planRules: FormRules = {
  title: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入计划描述", trigger: "blur" }],
  dueDate: [{ required: true, message: "请选择截止日期", trigger: "change" }],
};

// 模拟数据
const allPlans = ref([
  {
    id: "1",
    title: "考研数学复习计划",
    description: "系统复习高等数学、线性代数和概率统计",
    progress: 65,
    dueDate: "2024-06-01",
    createdAt: "2024-01-01",
    status: "active",
    tasks: [
      { id: "1", title: "高等数学第一章", duration: 120, completed: true },
      { id: "2", title: "高等数学第二章", duration: 120, completed: true },
      { id: "3", title: "线性代数基础", duration: 90, completed: false },
      { id: "4", title: "概率论基础", duration: 90, completed: false },
    ],
  },
  {
    id: "2",
    title: "Vue.js 深度学习",
    description: "掌握Vue.js框架的高级特性和最佳实践",
    progress: 30,
    dueDate: "2024-03-15",
    createdAt: "2024-01-10",
    status: "active",
    tasks: [
      {
        id: "1",
        title: "Vue3 Composition API",
        duration: 180,
        completed: true,
      },
      { id: "2", title: "Pinia状态管理", duration: 120, completed: false },
      { id: "3", title: "Vue Router 4", duration: 90, completed: false },
    ],
  },
  {
    id: "3",
    title: "英语四级备考",
    description: "提高英语听说读写能力，通过四级考试",
    progress: 100,
    dueDate: "2023-12-16",
    createdAt: "2023-10-01",
    completedAt: "2023-12-10",
    status: "completed",
    tasks: [
      { id: "1", title: "词汇积累", duration: 60, completed: true },
      { id: "2", title: "听力练习", duration: 90, completed: true },
      { id: "3", title: "阅读理解", duration: 120, completed: true },
    ],
  },
]);

const activePlans = computed(() =>
  allPlans.value.filter((plan) => plan.status === "active")
);

const completedPlans = computed(() =>
  allPlans.value.filter((plan) => plan.status === "completed")
);

const pausedPlans = computed(() =>
  allPlans.value.filter((plan) => plan.status === "paused")
);

const getCurrentPlans = () => {
  switch (activeTab.value) {
    case "active":
      return activePlans.value;
    case "completed":
      return completedPlans.value;
    case "paused":
      return pausedPlans.value;
    default:
      return [];
  }
};

const getEmptyMessage = () => {
  switch (activeTab.value) {
    case "active":
      return "暂无进行中的学习计划";
    case "completed":
      return "暂无已完成的学习计划";
    case "paused":
      return "暂无已暂停的学习计划";
    default:
      return "暂无学习计划";
  }
};

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${(date.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
};

const calculateDaysLeft = (dueDate: string) => {
  const due = new Date(dueDate);
  const now = new Date();
  const diffTime = due.getTime() - now.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return Math.max(0, diffDays);
};

const updateTaskStatus = (
  planId: string,
  taskId: string,
  completed: boolean
) => {
  const plan = allPlans.value.find((p) => p.id === planId);
  if (plan) {
    const task = plan.tasks.find((t) => t.id === taskId);
    if (task) {
      task.completed = completed;
      // 重新计算进度
      const completedTasks = plan.tasks.filter((t) => t.completed).length;
      plan.progress = Math.round((completedTasks / plan.tasks.length) * 100);
    }
  }
};

const handlePlanAction = (command: string) => {
  const [action, planId] = command.split(":");

  switch (action) {
    case "edit":
      editPlan(planId);
      break;
    case "pause":
      pausePlan(planId);
      break;
    case "delete":
      deletePlan(planId);
      break;
  }
};

const editPlan = (planId: string) => {
  ElMessage.info("编辑功能开发中");
};

const pausePlan = (planId: string) => {
  const plan = allPlans.value.find((p) => p.id === planId);
  if (plan) {
    plan.status = "paused";
    ElMessage.success("计划已暂停");
  }
};

const resumePlan = (planId: string) => {
  const plan = allPlans.value.find((p) => p.id === planId);
  if (plan) {
    plan.status = "active";
    ElMessage.success("计划已恢复");
  }
};

const deletePlan = (planId: string) => {
  ElMessageBox.confirm("确定要删除这个学习计划吗？", "确认删除", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const index = allPlans.value.findIndex((p) => p.id === planId);
    if (index > -1) {
      allPlans.value.splice(index, 1);
      ElMessage.success("计划已删除");
    }
  });
};

const viewPlanDetail = (plan: any) => {
  ElMessage.info("详情页面开发中");
};

const startStudy = (plan: any) => {
  userStore.setCurrentStudyPlan(plan);
  router.push("/study-room/list");
};

const addTask = () => {
  planForm.tasks.push({
    title: "",
    duration: 60,
    completed: false,
  });
};

const removeTask = (index: number) => {
  planForm.tasks.splice(index, 1);
};

const createPlan = async () => {
  if (!planFormRef.value) return;

  try {
    await planFormRef.value.validate();
    creating.value = true;

    const newPlan = {
      id: Date.now().toString(),
      title: planForm.title,
      description: planForm.description,
      progress: 0,
      dueDate: planForm.dueDate,
      createdAt: new Date().toISOString(),
      status: "active",
      tasks: planForm.tasks.map((task, index) => ({
        id: (index + 1).toString(),
        title: task.title,
        duration: task.duration,
        completed: false,
      })),
    };

    allPlans.value.unshift(newPlan);
    showCreateDialog.value = false;
    ElMessage.success("学习计划创建成功");

    // 重置表单
    Object.assign(planForm, {
      title: "",
      description: "",
      dueDate: "",
      tasks: [{ title: "", duration: 60, completed: false }],
      aiAssisted: true,
    });
  } catch (error) {
    ElMessage.error("请填写完整信息");
  } finally {
    creating.value = false;
  }
};
</script>

<style scoped>
.study-plan {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 40px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
  font-size: 2.5rem;
}

.plan-tabs {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-top: 24px;
}

.plan-card {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.3s ease;
}

.plan-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.plan-card.completed {
  background: #f0f9ff;
  border-color: #67c23a;
}

.plan-card.paused {
  background: #fdf6ec;
  border-color: #e6a23c;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.plan-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.plan-description {
  color: #7f8c8d;
  line-height: 1.5;
  margin-bottom: 20px;
}

.plan-progress {
  margin-bottom: 20px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #7f8c8d;
}

.plan-tasks {
  margin-bottom: 20px;
}

.tasks-header {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 12px;
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
}

.task-duration {
  color: #909399;
  font-size: 12px;
}

.more-tasks {
  color: #909399;
  font-size: 12px;
  text-align: center;
  padding: 8px;
}

.plan-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #7f8c8d;
  font-size: 14px;
}

.completion-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #67c23a;
  font-size: 14px;
  margin-top: 12px;
}

.plan-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state p {
  margin: 20px 0;
  font-size: 16px;
}

.tasks-editor {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.task-editor {
  display: flex;
  gap: 12px;
  align-items: center;
}

@media (max-width: 768px) {
  .plans-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .plan-tabs {
    padding: 20px;
  }

  .task-editor {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
